<?php

declare(strict_types=1);

namespace App\CustHub\Middleware;

use Mine\MineRequest;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Server\MiddlewareInterface;

class AddParamsMiddleware implements MiddlewareInterface
{

    protected $noNeedAdd = [

    ];

    public function process(Request $request, Handler $handler): Response
    {
        try {
            $userInfo = chUser()->getUserInfo();
            $mainUid = $userInfo['parent_id'] == 0 ? $userInfo['id'] : $userInfo['parent_id'];
            $original_uid = $request->getParsedBody()['uid'] ?? 0;
            $pageSize = $request->getParsedBody()['page_size'] ?? 10;
            // 追加主账号参数
            $request = $request->withParsedBody(array_merge($request->getParsedBody() ?? [], [
                'uid' => (int) $userInfo['id'],
                'main_uid' => (int) $mainUid,
                'original_uid' => (int) $original_uid,
                'page_size' => (int) $pageSize,
            ]));
        }catch (\Throwable $e){
            //无须追加参数
        }
        return $handler->handle($request);
    }
}